import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/server/ws/ws_manager.dart';
import 'package:ball_lion/utils/date_time_utils.dart';

class SocketTestController extends GetxController {
  ScrollController scrollController = ScrollController();

  void toEnd() {
    scrollController.animateTo(scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 200), curve: Curves.easeIn);
  }
}

class SocketPage extends StatefulWidget {
  const SocketPage({super.key});

  @override
  State<SocketPage> createState() => _SocketPageState();
}

class _SocketPageState extends State<SocketPage> {
  List<String> message = [];
  ScrollController scrollController = ScrollController();
  SocketTestController logic = Get.put(SocketTestController());

  @override
  void initState() {
    WebSocketManager.messageStream.listen((event) {
      setState(() {
        message.add(
            "${DateTime.now().formatedString("HH:mm:ss.SSS")} ${jsonEncode(event)}");
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SocketTestController>(
      builder: (GetxController controller) => Scaffold(
        appBar: Styles.appBar(title: const Text("Socket测试")),
        body: ListView.builder(
          controller: logic.scrollController,
          itemCount: WebSocketManager.record.length,
          itemBuilder: (BuildContext context, int index) {
            return Text(WebSocketManager.record[index]);
          },
        ),
      ),
    );
  }
}
